<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card>
      <!-- 警告提示框 -->
      <el-alert title="注意：只允许为第三级分类设置相关参数！" type="warning" :closable="false"></el-alert>
      <!-- 选择商品分类区域 -->
      <el-row class="cat-opt">
        <el-col>
          <span>选择商品分类：</span>
          <!-- 选择商品分类的级联选择器 -->
          <!-- v-model  选中项绑定值 存储的是props 里面value对应的属性值 数组的格式 -->
          <!-- options  数据源 -->
          <!-- props  配置选项 -->
          <el-cascader v-model="cateSelected" :options="cateList" :props="cateProps" @change="handleChange">
          </el-cascader>
        </el-col>
      </el-row>
      <!-- 动态标签 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <!-- 动态参数面板 -->
        <el-tab-pane label="动态参数" name="many">
          <el-button type="primary" :disabled='isBtnDisabled' @click="addManyDialog">添加参数</el-button>
          <!-- 动态参数表格 -->
          <el-table :data="manyTableData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- for 循环生成 tag标签 -->
                <el-tag v-for="(item, i) in scope.row.attr_vals" :key="i" closable @close="handelClose(i,scope.row)">
                  {{item}}</el-tag>
                <!-- 点击生成tag标签 -->
                <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue"
                  ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)">
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag
                </el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="attr_name" label="参数名称">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="editBtn(scope.row.attr_id)">编辑
                </el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteParam(scope.row.attr_id)">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- 静态属性面板 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button type="primary" :disabled='isBtnDisabled' @click="addOnlyDialog">添加属性</el-button>
          <!-- 静态属性表格 -->
          <el-table :data="onlyTableData" border stripe>
            <!-- 展开行 -->
             <el-table-column type="expand">
              <template slot-scope="scope">
                <!-- for 循环生成 tag标签 -->
                <el-tag v-for="(item, i) in scope.row.attr_vals" :key="i" closable @close="handelClose(i,scope.row)">
                  {{item}}</el-tag>
                <!-- 点击生成tag标签 -->
                <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue"
                  ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)">
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag
                </el-button>
              </template>
            </el-table-column>
            <!-- 索引行 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="attr_name" label="属性名称">
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit" size="mini" @click="editBtn(scope.row.attr_id)">编辑
                </el-button>
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteParam(scope.row.attr_id)">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加参数的对话框 -->
    <el-dialog :title="'添加'+this.titleText" :visible.sync="adddialogVisible" width="50%" @close="addDialogClosed">
      <!-- 表单 -->
      <el-form :model="addForm" :rules="addFormRule" ref="addFormRef" label-width="100px">
        <el-form-item :label="this.titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="adddialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveAdd">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改参数的对话框 -->
    <el-dialog :title="'编辑'+this.titleText" :visible.sync="editdialogVisible" width="50%" @close="editDialogClosed">
      <!-- 表单 -->
      <el-form :model="editForm" :rules="editFormRule" ref="editFormRef" label-width="100px">
        <el-form-item :label="this.titleText" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveEdit">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        // 商品分类数据
        cateList: [],
        // 级联选择器选中项的绑定值
        cateSelected: [],
        // 级联选择器的配置选项
        cateProps: {
          // 次级菜单的展开方式
          expandTrigger: 'hover',
          // 指定选项的值为选项对象的某个属性值  填写数据源的属性
          value: 'cat_id',
          // 指定选项标签为选项对象的某个属性值
          label: 'cat_name',
          // 指定选项的子选项为选项对象的某个属性值
          children: 'children'
        },
        // 被激活的页签名称
        activeName: 'many',
        // 动态参数的数据
        manyTableData: [],
        // 静态参数的数据
        onlyTableData: [],
        // 添加参数的对话框的显示与隐藏
        adddialogVisible: false,
        // 添加参数的表单
        addForm: {
          attr_name: ''
        },
        // 添加参数的表单规则
        addFormRule: {
          attr_name: [{
            required: true,
            message: "请输入名称",
            trigger: 'blur'
          }]
        },
        // 修改参数的对话框的显示与隐藏
        editdialogVisible: false,
        // 编辑参数的表单
        editForm: {},
        // 编辑参数的表单规则
        editFormRule: {
          attr_name: [{
            required: true,
            message: "请输入名称",
            trigger: 'blur'
          }]
        }
      }
    },
    created() {
      this.getCateList()
    },
    methods: {
      // 获取商品分类数据
      async getCateList() {
        const {
          data: res
        } = await this.$http.get('categories')
        if (res.meta.status !== 200) {
          return this.$message.error('获取数据失败')
        }
        this.cateList = res.data
        // console.log(this.cateList);
      },
      // 级联选择器  当选中节点变化时触发
      handleChange() {
        this.getParamsData()
      },
      // 点击动态标签触发
      handleClick() {
        console.log(this.activeName);
        this.getParamsData()
      },
      // 获取参数列表数据
      async getParamsData() {
        // 判断不是三级分类
        if (this.cateSelected.length !== 3) {
          this.cateSelected = []
          return;
        }
        // console.log(this.cateSelected);
        const {
          data: res
        } = await this.$http.get(`categories/${this.cateId}/attributes`, {
          params: {
            sel: this.activeName
          }
        })
        if (res.meta.status !== 200) {
          return this.$message.error('获取失败')
        }

        // 将attr_vals 中的数据转换为数组
        res.data.forEach(item => {
          // 由于空字符串 ''.split(" ")= [""]，循环时，也会生成一个tag标签
          // 这里需要使用三元表达式判断是否为空
          item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []

          // 为每一个item 添加自己的属性
          // 生成tag标签中 文本框的显示与隐藏
          item.inputVisible = false
          // 文本框的内容
          item.inputValue = ''
        })
        console.log(res.data);

        if (this.activeName === 'many') {
          this.manyTableData = res.data
        }
        if (this.activeName === 'only') {
          this.onlyTableData = res.data
        }
      },
      // 添加动态参数按钮
      addManyDialog() {
        this.adddialogVisible = true
      },
      // 添加静态属性按钮
      addOnlyDialog() {
        this.adddialogVisible = true
      },
      // 添加参数的对话框关闭后
      addDialogClosed() {
        // 对表单进行清空
        this.$refs.addFormRef.resetFields()
      },
      // 添加提交参数
      saveAdd() {
        this.$refs.addFormRef.validate(async valid => {
          if (!valid) return;

          const {
            data: res
          } = await this.$http.post(`categories/${this.cateId}/attributes`, {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName
          })

          if (res.meta.status !== 201) {
            return this.$message.error('创建失败')
          }
          this.$message.success('创建成功')
          this.getParamsData();
          this.adddialogVisible = false
        })
      },
      // 编辑参数的对话框关闭后
      editDialogClosed() {
        this.$refs.editFormRef.resetFields()
      },
      // 编辑提交参数
      saveEdit() {
        this.$refs.editFormRef.validate(async valid => {
          if (!valid) return;
          const {
            data: res
          } = await this.$http.put(`categories/${this.cateId}/attributes/${this.editForm.attr_id}`, {
            attr_name: this.editForm.attr_name,
            attr_sel: this.activeName
          })

          if (res.meta.status !== 200) {
            return this.$message.error('编辑提交失败')
          }
          this.$message.success('编辑提交成功')
          this.getParamsData()
          this.editdialogVisible = false
        })
      },
      // 编辑参数按钮
      async editBtn(atterId) {
        // 根据 id 查询参数
        const {
          data: res
        } = await this.$http.get(`categories/${this.cateId}/attributes/${atterId}`)

        if (res.meta.status !== 200) {
          return this.$message.error('获取失败')
        }
        this.editForm = res.data
        this.editdialogVisible = true
      },
      // 删除参数按钮
      async deleteParam(id) {
        console.log(id);

        // 确认是否删除的弹框
        const confirmResult = await this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)

        if (confirmResult === 'cancel') {
          this.$message.info('已取消删除')
        }

        // 确定取消后的删除操作
        const {
          data: res
        } = await this.$http.delete(`categories/${this.cateId}/attributes/${id}`)
        if (res.meta.status !== 200) {
          return this.$message.error('删除失败')
        }
        this.$message.success('删除成功')
        this.getParamsData()
      },
      // 生成tag标签中，按回车或者失去焦点时触发
      async handleInputConfirm(row) {
        if (row.inputValue.trim().length == 0) {
          row.inputValue = ''
          row.inputVisible = false
          return
        }
        // 如果没有return 则证明输入的内容 需要做后续处理
        // 将input 中输入的内容 push 到数组中
        row.attr_vals.push(row.inputValue.trim())
        // 隐藏文本框
        row.inputVisible = false
        // 清空文本的内容
        row.inputValue = ''

        // 编辑提交参数
        this.saveAttrVals(row)
      },
      // 将对 attr_vals 的操作保存到数据库
      async saveAttrVals(row) {
        const {
          data: res
        } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' ')
        })

        if (res.meta.status !== 200) {
          this.$message.error('编辑数据失败')
        }
        this.$message.success('编辑数据成功')
      },

      // 点击生成tag标签时，显示文本框
      showInput(row) {
        row.inputVisible = true
        // 文本框自动获取焦点
        // this.$nextTick 是在页面重新渲染之后，才会执行里面的回调函数
        this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
      },
      // 删除标签触发
      handelClose(i, row) {
        // splice(index,num) 影响原来的数组
        row.attr_vals.splice(i, 1)
        // 编辑提交参数
        this.saveAttrVals(row)
      }
    },
    computed: {
      isBtnDisabled() {
        if (this.cateSelected.length === 3) {
          return false
        } else {
          return true
        }
      },
      // 获取第三级分类的标签Id
      cateId() {
        if (this.cateSelected.length === 3) {
          return this.cateSelected[2]
        } else {
          return null
        }
      },
      // 添加参数的 动态标题
      titleText() {
        if (this.activeName === 'many') {
          return "动态参数"
        }
        if (this.activeName === 'only') {
          return "静态参数"
        }
      }
    }
  }

</script>

<style lang="less" scoped>
  .cat-opt {
    margin: 15px 0px;
  }

  .el-tag {
    margin-right: 10px;
  }

  .input-new-tag {
    width: 120px;
  }

</style>
